import axios from 'axios'
import Promise from 'bluebird'
import token from '@/util/token'
import Cookies from 'js-cookie'

Promise.config({
  warnings: {
    wForgottenReturn: false
  },
  longStackTraces:false,
  cancellation: false,
  monitoring: false
});

const handleResponse = (res) => {
  if (res.data.success) {
    // 成功只返回data数据
    // return Promise.resolve(res.data.data)
    return Promise.resolve(res)
  } else {
    // status不为0为失败或错误情况
    return Promise.reject(res.data)
  }
}
const authority = (res) => {
    // 根据err_code 判断 是否有权限访问该页面的接口
    let body = res.body;
    if(body && $.isNumeric(body.error_code)) {
        body.error_code === 1 && ( window['vueObj'] && window['vueObj'].$router.replace({name: 'no_right'}) )
    }
    let data = res.data;
    if(data && $.isNumeric(data.error_code)) {
        data.error_code === 1 && ( window['vueObj'] && window['vueObj'].$router.replace({name: 'no_right'}) )
    }
}
export default {
  get (url, params) {
    let termStr = localStorage.getItem('currentTerm')
    let termObj =  termStr ? JSON.parse(termStr) : null

    let apiHeader = localStorage.getItem('API_HEADER');
    let apiHeaderObj = apiHeader? JSON.parse(apiHeader): null;

    params = params || {};
    var _xtbz = "xtbz" in params &&  params["xtbz"] || "";
    if(!params['no_term']){
      params['term'] = params['term'] ? params['term'] : termObj && termObj.value? termObj.value : 'latest'
    }

    params['uv_id'] =  params['uv_id']? params['uv_id']: apiHeaderObj && apiHeaderObj.school_id? apiHeaderObj.school_id: (Cookies.get("university_id")?Cookies.get("university_id"):'');

    let queryString = []
    Object.keys(params).forEach(key => params[key]!== undefined && queryString.push((`${key}=${params[key]}`)))
    if (queryString.length > 0) {
      queryString = queryString.join('&')
        if (url.indexOf('?') > -1) {
            url += `&${queryString}`
        } else {
            url += `?${queryString}`
        }
    }
    if(params['no_loading']) {
      //$('#global_loading').hide()
    } else {
      //$('#global_loading').show()
    }
    // return axios
    //   .get(url)
    //   .then(function (response, data) {
    //     $('#global_loading').hide()
    //     authority(response)
    //     return response
    //   })
    //   .then(handleResponse)
    //   .catch(error => {
    //     // 日志收集
    //     return Promise.reject(error)
    //   })
    let _header = {
      'xtbz': _xtbz ? _xtbz : Cookies.get('platform_id') == 8 ? 'training' : 'cloud',//业务线标识
      'university-id' : Cookies.get('university_id'),  //将cookie中的university_id放入header中
      //'platform-id': Cookies.get('platform_id') || 0,
    };
    if(Cookies.get("dep") && url.indexOf("dep") == -1){
      var _dep = Cookies.get("dep");
      if(_dep) url = url.indexOf("?") != -1 ? url + "&dep=" + _dep : url + "?dep=" + _dep;
    }
    return new Promise(function(resolve, reject){
        axios
        .get(url,{
          headers: _header
        })
        .then(function (response) {
          $('#global_loading').hide()
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    });
  },

  post (url, params) {
    let termStr = localStorage.getItem('currentTerm');
    let termObj =  termStr ? JSON.parse(termStr) : null;
    let term = termObj ? termObj.value : 'latest';

    let apiHeader = localStorage.getItem('API_HEADER');
    let apiHeaderObj = apiHeader? JSON.parse(apiHeader): null;

    params = params || {};
    let termParamsStr = `term=${params['term'] || term}`
    let uv_idParasStr = `uv_id=${apiHeaderObj && apiHeaderObj.school_id? apiHeaderObj.school_id: (Cookies.get("university_id")?Cookies.get("university_id"):'')}`
    if (url.indexOf('?') > -1) {
        url = `${url}&${termParamsStr}`
    } else {
        url += `?${termParamsStr}`
    }
    if (url.indexOf('uv_id') < 0) {
        url = `${url}&${uv_idParasStr}`
    }
    if(params['no_loading']) {
      //$('#global_loading').hide()
    } else {
      //$('#global_loading').show()
    }
    let _header = {
      'X-CSRFToken' : token(),
      'xtbz': Cookies.get('platform_id') == 8 ? 'training' : 'cloud', //业务线标识
      'university-id' : Cookies.get('university_id') || 0,  //将cookie中的university_id放入header中
      //'platform-id': Cookies.get('platform_id') || 0,
    };
    if(Cookies.get("dep") && url.indexOf("dep") == -1){
      var _dep = Cookies.get("dep");
      if(_dep) url = url.indexOf("?") != -1 ? url + "&dep=" + _dep : url + "?dep=" + _dep;
    }
    return axios
      .post(url, params,{
        headers : _header
      })
      .then(function (response) {
        $('#global_loading').hide()
        return response
      })
      .catch(error => {
        return Promise.reject(error)
      })
  }
}
